package com.ruoyi.excel.handle;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.excel.domain.AsyncImportExportTask;
import com.ruoyi.excel.service.AsyncTaskCommonService;
import com.ruoyi.excel.service.IAsyncImportExportTaskService;
import com.ruoyi.excel.utils.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author fjw
 * @date 2021-09-27
 */
@Component
@Slf4j
public class AsyncImExportDataHandle {

    static ThreadPoolExecutor.CallerRunsPolicy policy = new ThreadPoolExecutor.CallerRunsPolicy();


    static ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 4, 2, TimeUnit.SECONDS, new LinkedBlockingQueue<>(200), new ThreadFactory() {
        int num = 0;

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("async-task-thread-" + ++num);
            return thread;
        }
    }, policy);


    @Autowired
    private IAsyncImportExportTaskService asyncImportExportTaskService;

    @Async
    public void dealAsyncTask() {
        List<AsyncImportExportTask> list = asyncImportExportTaskService.getTaskAndUpdateStatusSynchronized();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        log.info("====> 需要处理任务条数：{}", list.size());
        for (AsyncImportExportTask asyncImportExportTask : list) {
            try {

                ((AsyncTaskCommonService) SpringContextHolder.getBean(asyncImportExportTask.getTaskCode()))
                    .invoke(asyncImportExportTask);
            } catch (Exception e) {
                log.error("invoke FileWriter error:", e);
            }
        }
    }
}
